import { getToken, setToken, getRoles, setRoles, removeAllKeys } from "../../utils/cookies.js"
import { login } from '../../api/user.js'
import { routes, userRoutes, adminRoutes } from '../../router/index.js'
//存储数据
function getCookiesRoles() {
	if (getRoles()) {
		return getRoles().split(',')
	} else {
		return []
	}
}
const state = {
	// userName:VueCookies.get('name')||'',
	token: getToken() || '',
	// avatar:VueCookies.get('avatar')||'',
	roles: getRoles()||[],
	role: [],
	sidebar: [],
}
//操作数据
const mutations = {
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	},
	SET_USERNAME: (state, userName) => {
		state.name = userName
	},
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_ROLES: (state, roles) => {
		state.roles = roles
	},
	SET_ROLE: (state, role) => {
		state.role = role
	},
}

const actions = {
	login(context, userInfo) {
		console.log('userInfo', userInfo)
		const { name, password } = userInfo
		return new Promise((resolve, reject) => {
			login(userInfo).then((request) => {
				console.log('request.data', request.data.data)
				const { token, roles, userInfo } = request.data.data
				context.commit('SET_TOKEN', token)
				context.commit('SET_ROLES', roles)
				context.commit('SET_AVATAR', userInfo.avatar)
				context.commit('SET_USERNAME', userInfo.userName)
				setToken(token)
				setRoles(roles)
				resolve(request)
			}).catch(error => {
				reject(error)
			})
		})
	},
	getRole({ commit }) {
		return new Promise((resolve, reject) => {
			commit('SET_ROLE', state.roles)
			resolve(state.roles)
		})
	},
	logout({ commit, state }) {
		return new Promise((resolve, reject) => {
			commit('SET_TOKEN', '')
			commit('SET_ROLES', [])
			removeAllKeys()
			resetRouter()
			resolve()

		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
